using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using YBBEST.Office365Portal.Core.SPListWS;

namespace YBBEST.Office365Portal.Core
{
    public interface IServiceConnection
    {
        void SetEndpoint<T>(ClientBase<T> client,string serviceName) where T:class;
        void SetOutgoingMessageProperties();
        void ConfigureAuthenticationRequestCookie();
    }

    public class ServiceConnection : IServiceConnection
    {
        private readonly IHttpRequestMessageBuilder builder;

        private readonly IMsOnlineClaimsHelper claimsHelper;
        private readonly string siteUrl;
        private HttpRequestMessageProperty p;

        public ServiceConnection(IProxyConfiguration configuration,IHttpRequestMessageBuilder builder,IMsOnlineClaimsHelper msOnlineClaimsHelper)
        {
            this.builder = builder;
            siteUrl = configuration.SiteUrl;
            claimsHelper = msOnlineClaimsHelper;
        }

        public void SetEndpoint<T>(ClientBase<T> client,string serviceName) where T:class 
        {
            client.Endpoint.Address = new EndpointAddress(serviceName);
        }

        public void SetOutgoingMessageProperties()
        {
            OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = p;
        }

        public void ConfigureAuthenticationRequestCookie() 
        {
            if (p != null) return;
            p = builder.Build();
            var cookie = claimsHelper.CookieContainer;
            string cookieHeader = cookie.GetCookieHeader(new Uri(siteUrl));
            p.Headers.Add("Cookie", cookieHeader);
        }
    }
}